<?php
namespace Application\Admin\Controller;

class Automate extends Base
{

    public function init()
    {
        $this->setDir('automate');
    }

    /*
        这里与早期的控制器方法不一样
    */
    public function initRoute($alias = '')
    {
        $data = [
            'path_new' => "/Admin/Automate/new?alias={$alias}",
            'path_edit' => "/Admin/Automate/edit?alias={$alias}",
            'path_index' => "/Admin/Automate/index?alias={$alias}",
            'path_show' => "/Admin/Automate/show?alias={$alias}",
            'path_delete' => "/Admin/Automate/delete?alias={$alias}"
        ];
        $this->setCommonData($data);
    }

    private function check($data)
    {
        $alias = $data['alias'];
        if(empty($alias)){
            $this->sendFail('PARAMETER_ERROR', 'alias参数错误');
        }
        $serviceModel = $this->get(SERVICE_MODEL);
        $model = $serviceModel->getModelByAlias($alias);
        if(empty($model)){
            $this->sendFail('PARAMETER_ERROR', '模型不存在');
        }
        $fields = $serviceModel->getFieldListByModel($model);
        if(empty($fields)){
            $this->sendFail('PARAMETER_ERROR', '模型没有字段');
        }
        $searchFields = $serviceModel->getSearchFieldListByModel($model);
        return [$alias, $serviceModel, $model, $fields, $searchFields];
    }

    private function makeVariableOrUrl($field)
    {
        return $this->get(SERVICE_AUTOMATE)->makeVariableOrUrl($field);
    }

    private function makeUrl($field)
    {
        return $this->get(SERVICE_AUTOMATE)->makeUrl($field);
    }

    private function makeNewOrEditForm($fields, $rs = null)
    {
        $html = [];
        foreach($fields as $v){
            $field = $v->dry_field_data;
            if($v->dry_add_edit_is_show == 0){
                continue;
            }
            /*如果是编辑*/
            if($rs){
                $field->dry_form_default = $rs->{$field->dry_field};
            }
            /*拼属性*/
            $variableOrUrl = $this->makeVariableOrUrl($field);
            $attribute = [];
            $attribute[] = "role='{$field->dry_form_type}'";
            $attribute[] = "label='{$field->dry_name}'";
            $attribute[] = "name='{$field->dry_field}'";
            if(in_array($field->dry_form_type, ['select', 'selectOnly'])){
                $attribute[] = "scene='{$v->dry_first_choice}'";
            }
            $attribute[] = "placeholder='{$field->dry_placeholder}'";
            $attribute[] = "help='{$field->dry_help}'";
            $attribute[] = "tip='{$field->dry_tip}'";
            if(!empty($variableOrUrl)){
                $attribute[] = $variableOrUrl;
            }
            /*文件选择需要iframeUrl*/
            if($field->dry_form_type == 'fileSelect'){
                $attribute[] = "iframeUrl='/Admin/File/index'";
            }
            $attribute = implode(' ', $attribute);
            $value = htmlspecialchars($field->dry_form_default);
            $html[] = "<dry-common {$attribute}><textarea style='display:none;'>{$value}</textarea></dry-common>";
        }
        $html = implode(PHP_EOL, $html);
        return $html;
    }

    private function makeAlias($alias = '')
    {
        return "?alias={$alias}";
    }

    private function getFieldWidth($modelField, $field)
    {
        $result = '';
        if(!empty($modelField->dry_field_width) && $modelField->dry_field_width != THE_NONE){
            $result = $modelField->dry_field_width;
        }
        if(!empty($field->dry_field_width) && $field->dry_field_width != THE_NONE){
            $result = $field->dry_field_width;
        }
        return $result;
    }

    private function getFieldTemplate($modelField, $field)
    {
        $result = '';
        if(!empty($modelField->dry_field_template) && $modelField->dry_field_template != THE_NONE){
            $result = $modelField->dry_field_template;
        }
        if(!empty($field->dry_field_template) && $field->dry_field_template != THE_NONE){
            $result = $field->dry_field_template;
        }
        return $result;
    }

    public function indexAction()
    {
        $data = $this->getRequestData();
        list($alias, , $model, $fields, $searchFields) = $this->check($data);
        usort($fields, function($c1, $c2){
            return compareValue($c1->dry_field_list_sort, $c2->dry_field_list_sort);
        });
        $html = [];
        if($model->dry_additional_column == 'radio'){
            $html[] = "{'type':'radio'}";
        }
        else if($model->dry_additional_column == 'checkbox'){
            $html[] = "{'type':'checkbox'}";
        }
        foreach($fields as $v){
            $field = $v->dry_field_data;
            $item = [];
            $item[] = "'title':'{$field->dry_name}'";
            /*是否用自定义模板显示*/
            $template = $this->getFieldTemplate($v, $field);
            if($template == ''){
                $item[] = "'field':'{$field->dry_field}'";
            }
            if($v->dry_is_init_hide){
                $item[] = "'hide':true";
            }
            if($v->dry_is_list_edit){
                $item[] = "'edit':'text'";
            }
            if($v->dry_is_list_click_sort){
                $item[] = "'sort':true";
            }
            if($template != ''){
                if($template == 'mergeRequestTag'){
                    $url = $this->makeUrl($field);
                    $item[] = "'templet':function(rs){return mergeRequest('tag', '{$field->dry_field}', rs.{$field->dry_field}, '{$url}', '', 1);}";
                }
                else if($template == 'mergeRequestFile'){
                    $url = $this->makeUrl($field);
                    $item[] = "'templet':function(rs){return mergeRequest('file', '{$field->dry_field}', rs.{$field->dry_field}, '{$url}', '/Admin/File/list', 0);}";
                }
                else if($template == 'indentShow'){
                    $item[] = "'templet':function(rs){return {$template}(rs.{$field->dry_field}, rs.dry_grade);}";
                }
                else{
                    $item[] = "'templet':function(rs){return {$template}(rs.{$field->dry_field});}";
                }
            }
            $width = $this->getFieldWidth($v, $field);
            if($width != ''){
                $item[] = "'width':{$width}";
            }
            $item = implode(',', $item);
            $html[] = '{' . $item . '}';
        }
        if($model->dry_index_operate_width == 'none'){
            $html[] = "{'title':'操作','toolbar':'#bar'}";
        }
        else{
            $html[] = "{'title':'操作','toolbar':'#bar','width':{$model->dry_index_operate_width}}";
        }
        $html = implode(',', $html);
        $html = "[{$html}]";
        $twigData = [];
        $twigData['alias'] = $this->makeAlias($alias);
        $twigData['html'] = $html;
        $twigData['limit'] = $model->dry_page_size;
        /*按钮 start*/
        $idIn = '-1,-2';
        if($model->dry_button != ''){
            $idIn = $model->dry_button;
        }
        $twigData['buttonList'] = $this->get(SERVICE_DRY)->makeButton($idIn);
        /*按钮 end*/
        /*搜索 start*/
        $twigData['searchCode'] = $this->get(SERVICE_DRY)->makeSearch($searchFields);
        /*搜索 end*/
        if(contain($model->dry_config, 'new')){
            $twigData['isIframe'] = 1;
        }
        else{
            $twigData['isIframe'] = 0;
        }
        $this->setFile($this->getTemplateIndex());
        $this->initRoute($alias);
        $this->setData($twigData);
        $this->show();
    }

    public function newAction()
    {
        $data = $this->getRequestData();
        list($alias, , $model, $fields, ) = $this->check($data);
        $twigData = [];
        $twigData['alias'] = $this->makeAlias($alias);
        $twigData['html'] = $this->makeNewOrEditForm($fields);
        $twigData['addEditLabelWidth'] = $model->dry_add_edit_label_width;
        $this->setFile($this->getTemplateNew());
        $this->initRoute($alias);
        $this->setData($twigData);
        $this->show();
    }

    public function editAction()
    {
        $data = $this->getRequestData();
        list($alias, , $model, $fields, ) = $this->check($data);
        $serviceAutomate = $this->get(SERVICE_AUTOMATE);
        $serviceAutomate->setReference($model);
        $rs = $serviceAutomate->one($data['id']);
        /*调用回调函数处理数据 start*/
        $serviceCallback = $this->get(SERVICE_CALLBACK);
        $rs = tryCall($serviceCallback, $alias, 'BeforeEditForShow', $rs, $serviceAutomate);
        /*调用回调函数处理数据 end*/
        $twigData = [];
        $twigData['alias'] = $this->makeAlias($alias);
        $twigData['html'] = $this->makeNewOrEditForm($fields, $rs);
        $twigData['rs'] = $rs;
        $twigData['addEditLabelWidth'] = $model->dry_add_edit_label_width;
        $this->setFile($this->getTemplateEdit());
        $this->initRoute($alias);
        $this->setData($twigData);
        $this->show();
    }

    public function showAction()
    {
        $data = $this->getRequestData();
        list($alias, , $model, $fields, ) = $this->check($data);
        usort($fields, function($c1, $c2){
            return compareValue($c1->dry_field_list_sort, $c2->dry_field_list_sort);
        });
        $serviceAutomate = $this->get(SERVICE_AUTOMATE);
        $serviceAutomate->setReference($model);
        $rs = $serviceAutomate->one($data['id']);
        /*调用回调函数处理数据 start*/
        $serviceCallback = $this->get(SERVICE_CALLBACK);
        $rs = tryCall($serviceCallback, $alias, 'BeforeShow', $rs, $serviceAutomate);
        /*调用回调函数处理数据 end*/
        $list = [];
        foreach($fields as $v) {
            $field = $v->dry_field_data;
            $name = $field->dry_name;
            $value = $rs->{$field->dry_field};
            $template = $this->getFieldTemplate($v, $field);
            if($template == ''){
                $list[] = ['name' => $name, 'field' => $field->dry_field, 'value' => $value, 'js' => ''];
            }
            else {
                if($template == 'mergeRequestTag'){
                    $url = $this->makeUrl($field);
                    $js = "\$\$('$field->dry_field').innerHTML = mergeRequest('tag', '{$field->dry_field}', rs.{$field->dry_field}, '{$url}', '', 1);";
                    $list[] = ['name' => $name, 'field' => $field->dry_field, 'value' => $value, 'js' => $js];
                }
                else if($template == 'mergeRequestFile'){
                    $url = $this->makeUrl($field);
                    $js = "\$\$('$field->dry_field').innerHTML = mergeRequest('file', '{$field->dry_field}', rs.{$field->dry_field}, '{$url}', '/Admin/File/list', 0);";
                    $list[] = ['name' => $name, 'field' => $field->dry_field, 'value' => $value, 'js' => $js];
                }
                else if($template == 'indentShow'){
                    $js = "\$\$('$field->dry_field').innerHTML = {$template}(rs.{$field->dry_field}, 1);";
                    $list[] = ['name' => $name, 'field' => $field->dry_field, 'value' => $value, 'js' => $js];
                }
                else{
                    $js = "\$\$('$field->dry_field').innerHTML = {$template}(rs.{$field->dry_field});";
                    $list[] = ['name' => $name, 'field' => $field->dry_field, 'value' => $value, 'js' => $js];
                }
            }
        }
        $width = $model->dry_show_label_width;
        if($width == THE_NONE){
            $width = 200;
        }
        else{
            $width = constant($width);
        }
        $this->setFile($this->getTemplateShow());
        $this->setData(['alias' => $alias, 'list' => $list, 'rs' => json_encode($rs), 'width' => $width]);
        $this->show();
    }

    public function deleteAction()
    {
        $data = $this->getRequestData();
        list(, , $model, , ) = $this->check($data);
        $serviceAutomate = $this->get(SERVICE_AUTOMATE);
        $serviceAutomate->setReference($model);
        $serviceAutomate->delete($data['ids']);
        $this->sendSuccess();
    }

}